import { getConfirmUpdatePrice } from '@/api/prepaidCard'
import { XBusinesslineId } from '@/constants'
import { OrderCouponInfo } from '@/types/orderCoupon'
import { SelectCardUpdatePriceParam, SelectCardUpdatePriceResponse } from '@/types/prepaidCard'
import { useAsyncEffect } from 'ahooks'
import { decode } from 'js-base64'
import React, { FC, useEffect, useState } from 'react'

export const useCouponsPrise = (
  paramTmp: Partial<SelectCardUpdatePriceParam>,
  orderCouponInfo: Partial<OrderCouponInfo>,
  balance: string,
) => {
  const [confirmPriseData, setConfirmPriseData] = useState<SelectCardUpdatePriceResponse>()
  const product_info = orderCouponInfo?.product_list?.map((val) => {
    return {
      product_id: val.product_id,
      price: val.price,
      product_num: 1,
      brand: 100,
    }
  })
  const selectOrderIdList = orderCouponInfo.order_coupon_list?.filter(
    (val) => val.is_checked == true && val.is_valid === true,
  )
  const selectCashIdList = orderCouponInfo.cash_coupon_list?.filter(
    (val) => val.is_checked == true && val.is_valid === true,
  )
  const choose_user_coupons = selectOrderIdList
    ?.map((val) => {
      return { user_coupon_id: val.user_coupon_id }
    })
    .concat(
      selectCashIdList?.map((val) => {
        return { user_coupon_id: val.user_coupon_id }
      }) || [],
    )

  const param = {
    ...paramTmp,
    product_info: decode(JSON.stringify(product_info)),
    use_gold: '1',
    balance: balance.toString(),
    choose_user_coupons: choose_user_coupons,
    'X-Businessline-Id': XBusinesslineId,
  }

  useAsyncEffect(async () => {
    const res = await getConfirmUpdatePrice(param)
    setConfirmPriseData(res)
  }, [])

  return [confirmPriseData, setConfirmPriseData]
}
